package org.openkoala.koala.popup.generatecode;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.SelectionDialog;
/**
 * 项目选择的对话框
 * @author lingen
 *
 */
public class ProjectSelectionDialog extends SelectionDialog {

	private Tree projectTree;
	private IJavaProject[] projects;

	protected ProjectSelectionDialog(Shell parentShell, IJavaProject[] projects) {
		super(parentShell);
		this.projects = projects;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = (Composite) super.createDialogArea(parent);

		GridData treeGridData = new GridData(300, 300);
		projectTree = new Tree(composite, SWT.SINGLE);
		projectTree.setLayoutData(treeGridData);

		for (IJavaProject project : projects) {
			TreeItem projectNode = new TreeItem(projectTree, SWT.NONE);
			projectNode.setData(project);
			projectNode.setText(project.getProject().getName());
			projectNode.setImage(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT).createImage());
			// IPackageFragmentRoot packageFragmentsRoot =
			// project.getPackageFragmentRoot(project.getPath().append("src/main/java").toString());
			// // for (IPackageFragment packagefragment : packageFragments) {
			// System.out.println(packageFragmentsRoot.getElementName());
			// // }
		}

		return composite;
	}
	
	@Override
	protected void okPressed() {
		TreeItem[] treeItems = projectTree.getSelection();
		if (treeItems == null || treeItems.length == 0) {
			MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR);
			messageBox.setMessage("请选择项目");
			messageBox.open();
		}
		
		IJavaProject project = (IJavaProject) treeItems[0].getData();
		
		List<IPath> selectionPath = new ArrayList<IPath>();
		selectionPath.add(project.getPath());
		setResult(selectionPath);
		
		super.okPressed();
	}

}
